package secondary_classes;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class SortedList extends ArrayList<Order> {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2977509790191004317L;
	private Comparator<Order> comp;
	
	public SortedList(Comparator<Order> comparator) {
		super();
		this.comp = comparator;
	}
 
	/* (non-Javadoc)
	 * @see java.util.ArrayList#add(java.lang.Object)
	 */
	@Override
	public boolean add(Order e) {
		boolean inserted = false;
		
		int insertionPoint = Collections.binarySearch(this, e, comp);
		
		if (insertionPoint < 0) {
			insertionPoint = -1 - insertionPoint;
		}
		
		//if (insertionPoint < this.size()) {
		//	if (!e.exactMatch(this.get(insertionPoint))) {
		//		this.add(insertionPoint, e);
		//		inserted = true;
		//	}
		//} else {
			this.add(insertionPoint, e);
			inserted = true;
		//}
			
//		if (e != null) {
//			for (int i = 0; i < this.size() && !inserted; i++) {
//				if (comp.compare(this.get(i), e) >= 0) {
//					this.add(i, e);
//					inserted = true;
//				}
//			}
//			if (!inserted) {
//				this.add(this.size(), e);
//				inserted = true;
//			}
//		}
		
		return inserted;
	}

	/* (non-Javadoc)
	 * @see java.util.ArrayList#addAll(java.util.Collection)
	 */
	@Override
	public boolean addAll(Collection<? extends Order> c) {
		for (Order o : c) {
			this.add(o);
		}
		
		return true;
	}

	/* (non-Javadoc)
	 * @see java.util.ArrayList#addAll(int, java.util.Collection)
	 */
	@Override
	public boolean addAll(int index, Collection<? extends Order> c) {
		return this.addAll(c);
	}
	
}
